package cn.hubujyjs.trainingapp.service.impl;

import cn.hubujyjs.trainingapp.dto.LoginDto;
import cn.hubujyjs.trainingapp.dto.UserDto;
import cn.hubujyjs.trainingapp.entity.User;
import cn.hubujyjs.trainingapp.mapper.UserMapper;
import cn.hubujyjs.trainingapp.service.SmsService;
import cn.hubujyjs.trainingapp.service.UserService;
import cn.hubujyjs.trainingapp.utils.R;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import static cn.hubujyjs.trainingapp.utils.Constants.USER_NAME_PREFIX;
import static cn.hubujyjs.trainingapp.utils.RedisConstants.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SmsService smsService;
    @Override
    public R sendCode(String phone) {
        if (!PhoneUtil.isMobile(phone)){
            return R.fail("手机号格式错误");
        }
        //6位数字验证码
        String s = RandomUtil.randomNumbers(6);
        //保存到redis
        redisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,s,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        smsService.sendCode(phone,s);
        return R.ok().msg("验证码发送成功");
    }

    @Override
    public R login(LoginDto login) {
        String phone = login.getPhone();
        String code = login.getCode();
        String password = login.getPassword();

        if (!PhoneUtil.isMobile(phone)){
            return R.fail("手机号格式错误");
        }
        User user;
        //验证码登录
        if (StrUtil.isNotBlank(code)){
            String s = redisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
            if (s == null || !s.equals(code)) {
                return R.fail("验证码错误或验证码已过期");
            }
            //查询用户
            user = getUser(phone);
            //用户不存在，注册
            if (user==null){
                user = createUserWithPhone(phone);
            }
        }else if (StrUtil.isNotBlank(password)){
            //密码登录（必须是已注册且设置密码的用户）
            user = getUser(phone);
            if (user==null){
                return R.fail("用户未注册，请先注册");
            }
            String passwordCrypt = user.getPassword();
            boolean b = DigestUtil.bcryptCheck(password, passwordCrypt);
            if (!b) {
                //TODO 登录重试次数，防止暴力穷举密码
                return R.fail("密码错误，请重新登录");
            }
        }else {
            return R.fail("请求参数错误");
        }
        //保存用户信息到 redis中
        String token = UUID.randomUUID().toString(true);
        UserDto userDTO = BeanUtil.copyProperties(user, UserDto.class);
        //将user转换成dto
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        String tokenKey = LOGIN_USER_KEY + token;
        redisTemplate.opsForHash().putAll(tokenKey, userMap);
        //设置token有效期
        redisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.DAYS);

        return R.ok(token);
    }

    @Override
    public R logout(String authorization) {
        redisTemplate.delete(LOGIN_USER_KEY+authorization);
        return R.ok("退出登录成功");
    }

    /**
     * 根据手机号查询用户
     * @param phone 手机号
     * @return 用户
     */
    private User getUser(String phone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        return this.getOne(wrapper);
    }

    /**
     * 手机号注册
     * @param phone 手机号
     * @return 注册用户
     */
    private User createUserWithPhone(String phone) {
        User user=new User();
        user.setPhone(phone);
        //设置随机用户名
        user.setUsername(USER_NAME_PREFIX+RandomUtil.randomString(6));
        this.save(user);
        return user;
    }
}
